<template>
  <AutoHeight>
    <el-header>
      <h2>{{ store.name }},欢迎您</h2>
      <div class="flex">
        <el-avatar :size="40" v-if="store.avatar" :src="store.avatar" />
        <el-button type="primary" @click="logout">退出</el-button>
      </div>
    </el-header>
    <el-container>
      <div class="aside">
        <el-menu
          active-text-color="#ffd04b"
          background-color="#545c64"
          class="el-menu-vertical-demo"
          :default-active="cur"
          text-color="#fff"
          :collapse="collapse"
          @select="handleSelect"
        >
          <MenuItemView v-for="menu in menus" :key="menu.path" :item="menu" :cur="cur" />
        </el-menu>
        <el-icon :class="getCollapseBtnClass()" @click="toggleCollapse"><Back /></el-icon>
      </div>
      <el-main>
        <RouterView />
      </el-main>
    </el-container>
  </AutoHeight>
</template>

<script setup lang="ts">
import { RouterView, useRouter } from 'vue-router' // eslint-disable-line
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { userStore } from '@/stores/user'
import { routesToMenus } from '@/tools'
import { routes } from '@/router'
import AutoHeight from '@/components/AutoHeight.vue'
import MenuItemView from '@/components/MenuItemView.vue'
import type { MenuItem, RouteItem } from '@/types/global.d'
const store = userStore()
const router = useRouter()
const cur = ref(location.pathname)
const menus = reactive<MenuItem[]>(routesToMenus(routes as RouteItem[], '')[0].children as MenuItem[])
const changeRoute = (path: string) => {
  cur.value = path
  router.push({ path })
}
const handleSelect = (key: string) => {
  changeRoute(key)
}
const logout = () => {
  // @ts-ignore
  store.setUserInfo('', '', '')
  router.push('/login')
}
// 处理菜单折叠相关逻辑
const collapse = ref(false)
const toggleCollapse = () => {
  collapse.value = !collapse.value
}
const getCollapseBtnClass = () => {
  return collapse.value ? 'rotate' : ''
}
// 加载时建立webSocket连接
const ws = ref<WebSocket | null>(null)
import { webSocketStore } from '@/stores/webSocket'
const socketStore = webSocketStore()
// import WebSocketClient from '@/tools/websocket.js'

onMounted(() => {
  // @ts-ignore
  const mode = import.meta.env.MODE
  // let ws: WebSocket | null = null
  const url = mode === 'development' ? 'ws://localhost:3000' : 'wss://www.liqiantw.icu:3000'
  ws.value = new WebSocket(url)
  // ws.value = new WebSocketClient(url).ws
  socketStore.setInstance(ws.value)

  // 发送心跳包
  function sendPing() {
    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
      ws.value.send(JSON.stringify({ type: 'ping' }))
    }
  }

  // 设置定时器，每隔一段时间发送一次心跳
  setInterval(sendPing, 30000) // 每30秒发送一次

  ws.value.onopen = function(event: any) {
    console.log('WebSocket Connection established!', event)
  }

  ws.value.onerror = function(error: any) {
    console.error('WebSocket Error:', error)
  }

  ws.value.onmessage = function(event: any) {
    socketStore.setMessage(event.data)
  }
  ws.value.onclose = function() {
    console.log('WebSocket Connection closed')
  }
})
onUnmounted(() => {
  ws.value?.close()
  socketStore.setMessage({})
  socketStore.setInstance(null)
})
</script>
<style scoped lang="less">
.el-header {
  flex-shrink: 0;
  border-bottom: 1px solid #000;
  display: flex;
  align-items: center;
  justify-content: space-between;

  h1 {
    margin: 0;
    line-height: 50px;
  }
  .flex {
    display: flex;
    align-items: center;
    .el-button {
      margin-left: 10px;
    }
  }
}

.el-container {
  flex: 1;
  overflow: hidden;
}
.aside {
  position: relative;
  & > .el-icon {
    position: absolute;
    bottom: 5px;
    right: 5px;
    font-size: 18px;
    color: skyblue;
    &.rotate {
      transform: rotate(180deg);
    }
  }
}
.el-menu.el-menu--vertical.el-menu-vertical-demo {
  height: 100%;
  overflow-y: auto;
}
:deep(.el-main) {
  padding-bottom: 0px !important;
  overflow-y: hidden;
}
</style>
